//wxPromise.js
/**
 * 授权检测
 * @param authStr
 * @param msg
 * @returns {Promise<unknown>}
 */
 function authorize(authStr, msg = '是否去权限管理页打开授权') {
    return new Promise((resolve, reject) => {
        wx.getSetting({
            success(res) {
                if (res.authSetting[authStr]) {
                    //已经授权
                    resolve()
                } else if (res.authSetting[authStr] === undefined) {
                    //未授权
                    wx.authorize({
                        scope: authStr,
                        success: res => { //同意授权
                            resolve(res)
                        },
                        fail: res => { //拒绝授权
                            reject(res)
                        }
                    })
                } else if (res.authSetting[authStr] === false) {
                    //已拒绝授权，弹框让用户去授权管理页打开
                    wxModal({
                        title: '权限管理',
                        content: msg
                    }).then(() => {
                        wx.openSetting({//打开授权管理页
                            success(res) {
                                if (res.authSetting[authStr]) {//再次判断用户是否授权
                                    resolve()
                                } else {
                                    reject(res)
                                }
                            },
                            fail(res) {
                                reject(res)
                            }
                        })
                    }).catch(() => {
                        reject()
                    })
                }
            },
            fail(res) {
                reject(res)
            }
        })
    })
}
/**
 * 对话框
 * @param params
 * @returns {Promise<unknown>}
 */
function wxModal(params) {
    if (typeof params === 'string') params = {title: params}
    return new Promise((resolve, reject) => {
        wx.showModal({
            ...params,
            success(res) {
                if (res.confirm) {
                    resolve()
                } else {
                    reject()
                }
            },
            fail() {
                reject()
            }
        })
    })
}
/**
 * 加载框
 * @param object
 */
function wxLoading(object = {}) {
    let defaultObject = {
        title: '正在加载',
        mask: true
    }
    object = typeof object === 'string' ? {
        ...defaultObject,
        title: object,
    } : {
        ...defaultObject,
        ...object
    }
    wx.showLoading(object)
}
/**
 * 隐藏加载框
 */
function wxHide() {
    wx.hideLoading()
}
/**
 * 消息提示框
 * @param object
 */
function wxToast(object = {}) {
    let defaultObject = {
        title: '',
        mask: false,
        icon: 'none',
        duration: 2000
    }
    object = typeof object === 'string' ? {
        ...defaultObject,
        title: object,
    } : {
        ...defaultObject,
        ...object
    }
    wx.showToast(object)
}
/**
 * 获取登录code
 * @returns {Promise<unknown>}
 */
function wxLogin() {
    return new Promise((resolve, reject) => {
        wx.login({
            success(res) {
                console.info('wx登录获取用户code：')
                if (res.code) {
                    console.info(res.code)
                    resolve(res.code)
                } else {
                    reject(res)
                }
                resolve(res)
            },
            fail(err) {
                console.error('wx登录获取用户失败')
                reject(err)
            }
        })
    })
}
/**
 *获取图片信息
 * @param src
 */
function wxGetImageInfo(src) {
    return new Promise((resolve, reject) => {
        wx.getImageInfo({
            src,
            success(res) {
                resolve(res)
            },
            fail() {
                reject('获取图片信息失败')
            }
        })
    })
}

/**
 * 获取收货地址
 * @returns {Promise<unknown>}
 */
function wxChooseAddress() {
    return new Promise((resolve, reject) => {
        authorize('scope.address').then(() => {
            wx.chooseAddress({
                success(res) {
                    resolve(res)
                },
                fail() {
                    reject()
                }
            })
        }).catch(() => {
            reject()
        })
    })
}

/**
 * 微信支付
 * @param params
 * @returns {Promise<unknown>}
 */
function wxRequestPayment(params) {
    return new Promise((resolve, reject) => {
        wx.requestPayment({
            'timeStamp': params.timeStamp,
            'nonceStr': params.nonceStr,
            'package': params.package,
            'signType': params.signType,
            'paySign': params.paySign,
            'success': res => {
                resolve(params)
            },
            'fail': err => {
                reject(err)
            }
        })
    })
}

/**
 * 页面跳转
 * @param url
 * @param events
 * @returns {Promise<unknown>}
 */
function wxNavigate(url, events = {}) {
    return new Promise((resolve, reject) => {
        wx.navigateTo({
            url,
            events,
            success(res) {
                resolve(res)
            },
            fail(res) {
                reject(res)
            }
        })
    })
}

/**
 * 查看图片
 * @param current
 * @param urls
 */
function wxPreview(current, urls) {
    if (urls.length === 0) {
        wxToast('图片列表为空')
        return
    }
    wx.previewImage({
        current: urls[current],
        urls
    })
}
/**
 * 复制内容到粘贴板
 * @param msg 需要复制的内容
 */
function wxCopy(msg) {
    return new Promise((resolve, reject) => {
        wx.setClipboardData({
            data: msg,
            success() {
                resolve()
            },
            fail() {
                reject()
            }
        })
    })
}
/**
 * 微信扫码
 */
function wxScanCode(params = {}) {
    return new Promise((resolve, reject) => {
        wx.scanCode({
            ...params,
            success(res) {
                resolve(res)
            },
            fail(err) {
                reject(err)
            }
        })
    })
}
/**
 * 保存图片到手机
 * @param url
 */
function wxSaveImageToPhotosAlbum(url) {
    return new Promise((resolve, reject) => {
        authorize('scope.writePhotosAlbum').then(() => {
            wx.saveImageToPhotosAlbum({
                filePath: url,
                success() {
                    resolve()
                },
                fail() {
                    reject()
                }
            })
        }).catch(() => {
            reject()
        })
    })
}
/**
 * 选择手机相册图片
 */
function wxChooseImage(params = {}) {
    return new Promise((resolve, reject) => {
        wx.chooseImage({
            ...params,
            success: res => {
                resolve(res)
            },
            fail: err => {
                reject(err)
            }
        });
    })
}
/**
 * 选择手机视频
 */
function wxChooseVideo(params = {}) {
    return new Promise((resolve, reject) => {
        wx.chooseVideo({
            ...params,
            success: res => {
                resolve(res)
            },
            fail: err => {
                reject(err)
            }
        })
    })
}
/**
 * 拨打电话
 */
function wxCall(phone) {
    wx.makePhoneCall({
        phoneNumber: phone //仅为示例，并非真实的电话号码
    })
}
/**
 * 获取当前地理位置
 */
function wxGetLocation() {
    return new Promise((resolve, reject) => {
        authorize('scope.userLocation').then(() => {
            wx.getLocation({
                success: res => {
                    resolve(res)
                },
                fail: err => {
                    reject(err)
                }
            })
        }).catch(() => reject())
    })
}
/**
 * 打开微信内置地图
 */
function wxOpenLocation(params = {}) {
    return new Promise((resolve, reject) => {
        wx.openLocation({
            name: '',
            scale: 18,
            address: '',
            ...params,
            success(res) {
                resolve(res)
            },
            fail(err) {
                reject(err)
            }
        })
    })
}
/**
 * 打开地图选择位置。
 */
function wxChooseLocation(params = {}) {
    return new Promise((resolve, reject) => {
        authorize('scope.userLocation').then(() => {
            wx.chooseLocation({
                ...params,
                success(res) {
                    resolve(res)
                },
                fail(err) {
                    reject(err)
                }
            })
        }).catch(() => {
            reject()
        })
    })
}
/**
 * 跳转到其他小程序
 * @param appId
 * @param path
 * @param extraData
 * @param envVersion
 * @returns {Promise<unknown>}
 */
function wxToMini(appId, path = '', extraData = {}, envVersion = 'release') {
    return new Promise((resolve, reject) => {
        if (/^wx.*$/.test(appId)) {
            wx.navigateToMiniProgram({
                appId,
                path,
                extraData,
                envVersion,
                success(res) {
                    resolve(res)
                },
                fail(err) {
                    console.log(err);
                    reject(err)
                }
            })
        } else {
            reject('appId格式错误')
        }
    })
}
//获取系统信息
function wxGetSystemInfo() {
    return new Promise((resolve, reject) => {
        wx.getSystemInfo({
            success: res => {
                resolve(res)
            },
            fail: () => {
                reject()
            }
        })
    })
}
//返回上一页
function wxBack(params = {}) {
    wx.navigateBack({
        ...params,
        fail() {
            wxLinkTo('/pages/index/index', 'switchTab')
        }
    })
}
//路由跳转
function wxLinkTo(url, type = '') {
    if (url && url !== '#') {
        switch (type) {
            case "switchTab":
            case "tab":
                wx.switchTab({url})
                break
            case "reLaunch":
                wx.reLaunch({url})
                break
            case "redirectTo":
            case "redirect":
                wx.redirectTo({url})
                break
            case "navigateTo":
            case "push":
                wx.navigateTo({url})
                break
            default:
                wx.navigateTo({
                    url,
                    fail: () => {
                        if (/^wx.*$/.test(url)) {
                            let index = url.indexOf('?')
                            if (index > -1) {
                                wxToMini(url.slice(0, index), url.slice(index + 1))
                            } else {
                                wxToMini(url)
                            }
                        } else if (/^http.*$/.test(url)) {
                            wx.navigateTo({
                                url: `/package/tools/web-view/index?url=${url}`
                            })
                        } else {
                            setTabParams(url)
                            wx.switchTab({
                                url,
                                fail: () => {
                                    wx.removeStorage({
                                        key: 'tabParams'
                                    })
                                }
                            })
                        }
                    }
                })
        }
    }
}
/**
 * 如果是跳转tab页，需要处理tab页参数
 */
function setTabParams(url) {
    if (url.indexOf('?') > -1) {
        let paramStr = url.split('?')[1]
        let paramsArr = paramStr.split('&')
        let params = paramsArr.reduce((obj, item) => {
            if (item.indexOf('=') > -1) {
                let [key, value] = item.split('=')
                obj[key] = value
            }
            return obj
        }, {})
        if (params && JSON.stringify(params) !== '{}') {
            try {
                wx.setStorageSync('tabParams', params)
            } catch (e) {
                console.log(e);
            }
        } else {
            try {
                wx.removeStorageSync('tabParams')
            } catch (e) {
                console.log(e);
            }
        }
    }
}

/**
 * 获取tab参数
 */
function getTabParams() {
    try {
        const obj = wx.getStorageSync('tabParams')
        if (obj) {
            wx.removeStorage({
                key: 'tabParams'
            })
            return obj
        } else {
            return false
        }
    } catch (e) {
        return false
    }
}
function wxSetTabBarBadge(params) {
    return new Promise((resolve, reject) => {
        wx.setTabBarBadge({
            ...params,
            success(res) {
                resolve()
            },
            fail() {
                reject()
            }
        })
    })
}

function wxAudioPlayerState() {
    return new Promise((resolve, reject) => {
        wx.getBackgroundAudioPlayerState({
            success: (res) => resolve(res),
            fail: () => resolve()
        })
    })
}

/**
 * 获取本地缓存
 */
function wxGetStorage(key) {
    return new Promise(resolve => {
        wx.getStorage({
            key,
            success(res) {
                if (res.data) {
                    resolve(res.data)
                } else {
                    resolve(false)
                }
            },
            fail() {
                resolve(false)
            }
        })
    })
}

/**
 * 获取用户信息
 */
function wxGetUserProfile() {
    return new Promise((resolve, reject) => {
        wx.getUserProfile({
            desc: '完善个人信息',
            lang: 'zh_CN',
            success(res) {
                resolve(res.userInfo)
            },
            fail(err) {
                reject(err)
            }
        })
    })
}
module.exports = {
    authorize,
    wxModal,
    wxLoading,
    wxHide,
    wxToast,
    wxLogin,
    wxGetImageInfo,
    wxChooseAddress,
    wxRequestPayment,
    wxNavigate,
    wxPreview,
    wxCopy,
    wxScanCode,
    wxSaveImageToPhotosAlbum,
    wxChooseImage,
    wxChooseVideo,
    wxCall,
    wxGetLocation,
    wxOpenLocation,
    wxChooseLocation,
    wxToMini,
    wxGetSystemInfo,
    wxBack,
    wxLinkTo,
    setTabParams,
    getTabParams,
    wxSetTabBarBadge,
    wxAudioPlayerState,
    wxGetStorage,
    wxGetUserProfile
}
